package org.hepeng.workx.spring.orm.jpa;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


/**
 * @author he peng
 */

@Configuration
@ConditionalOnClass(JpaBaseConfiguration.class)
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
public class JpaCrossThreadShardEntityManagerAutoConfiguration {

    @Configuration
    @ConditionalOnWebApplication
    @ConditionalOnClass(WebMvcConfigurerAdapter.class)
    @ConditionalOnBean({ OpenEntityManagerInViewInterceptor.class,
            OpenEntityManagerInViewFilter.class })
    @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", havingValue = "true", matchIfMissing = true)
    protected static class JpaCrossThreadShardEntityManagerWebConfiguration extends WebMvcConfigurerAdapter {

        @Bean
        public TransactionalEntityManagerCachedInterceptor transactionalEntityManagerCachedInterceptor() {
            return new TransactionalEntityManagerCachedInterceptor();
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addWebRequestInterceptor(transactionalEntityManagerCachedInterceptor());
        }
    }
}
